#pragma once
#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <functional>

namespace ThreadMoudle
{
    // typedef void (*func_t)(const std::string &name);//提供线程名称的执行方法改名
    using func_t = std::function<void(std::string &name)>;
    class Thread
    {
    public:
        Thread(const std::string &name, func_t f)
            : _name(name), _func(f)
        {
            std::cout << "create thread_struct done" << std::endl;
        }
        void Execute()
        {
            isrunning = true;
            _func(_name);
            isrunning = false;
        }
        static void *ThreadRoutine(void *args)
        { // 相当于Java的run（）方法（代码源？？）
            Thread *self = (Thread *)args;
            self->Execute();
            return nullptr;
        }
        bool start()
        {
            int n = ::pthread_create(&_tid, nullptr, ThreadRoutine, this);
            if (n != 0)
            {
                perror("pthread_create");
                return false;
            }
            else
            {
                isrunning = true;
                return true;
            }
        }
        void stop()
        {
            if (isrunning)
            {
                isrunning = false;
                int n = ::pthread_cancel(_tid);
                if (n != 0)
                    perror("stop");
                else
                    std::cout << "quit success!" << std::endl;
            }
        }
        void join()
        {
            if (!isrunning)
            {
                int n = ::pthread_join(_tid, nullptr);
                if (n != 0)
                {
                    perror("join");
                }
                else
                {
                    std::cout << "wait success!" << std::endl;
                }
            }
        }
        ~Thread()
        {
            //最好不要
            // if (isrunning)
            // {
            //     this->stop();
            //     this->join();
            // }
        }

    private:
        std::string _name;
        pthread_t _tid; // 线程id
        bool isrunning = false;
        func_t _func; // 线程要执行的回调函数(外部传入)
    };
}